<template>
  <div class="app-container">
    <list-page
      :total="total"
      v-model:page-num="searchForm.pageNum"
      v-model:page-size="searchForm.pageSize"
      @getList="getList">
      <template #search>
        <list-search v-model="searchForm" @search="search">
          <el-form-item label="字典名称" prop="like.name" class="w-220px">
            <el-input v-model="searchForm.like.name" placeholder="请输入字典名称" clearable @keyup.enter="search" />
          </el-form-item>
          <el-form-item label="字典类型" prop="like.type" class="w-220px">
            <el-input v-model="searchForm.like.type" placeholder="请输入字典类型" clearable @keyup.enter="search" />
          </el-form-item>
          <el-form-item label="创建时间" prop="time.create_time" class="w-300px">
            <el-date-picker
              v-model="searchForm.time.create_time"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期" />
          </el-form-item>
        </list-search>
      </template>
      <template #actions>
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPerm="['system:dict-type:add']"
          >新增</el-button
        >
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="ids.length !== 1"
          @click="handleEdit"
          v-hasPerm="['system:dict-type:edit']"
          >修改</el-button
        >
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="!ids.length"
          @click="handleDelete"
          v-hasPerm="['system:dict-type:delete']"
          >删除</el-button
        >
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPerm="['system:dict-type:export']"
          >导出</el-button
        >
        <el-button type="danger" plain icon="Refresh" @click="handleRefreshCache" v-hasPerm="['system:dict-type:cache']"
          >刷新缓存</el-button
        >
      </template>
      <el-table v-loading="loading" :data="listData" @selection-change="handleSelection">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="编号" align="center" prop="id" width="60" />
        <el-table-column label="字典名称" align="center" prop="name" show-overflow-tooltip />
        <el-table-column label="字典类型" align="center" show-overflow-tooltip>
          <template v-slot="{ row }">
            <el-link :underline="false" type="primary" @click="toDictData(row)">{{ row.type }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
        <el-table-column label="创建时间" align="center" prop="create_time" width="140">
          <template v-slot="{ row }">{{ parseTime(row.create_time) }}</template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120" class-name="small-padding">
          <template v-slot="{ row }">
            <el-button link type="primary" icon="Edit" @click="handleEdit(row)" v-hasPerm="['system:dict-type:edit']"
              >修改</el-button
            >
            <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(row)"
              v-hasPerm="['system:dict-type:delete']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </list-page>
    <dict-form v-model="formShow" :row="formData" :module-name="moduleName" @submit="getList" v-if="formShow" />
  </div>
</template>

<script setup name="Dict">
  import { checkPerm } from '@/utils/auth'
  import useDictStore from '@/store/modules/dict'
  import { listTypeApi, delTypeApi, refreshCacheApi, exportTypeApi } from '@/api/system/dict/type'
  import DictForm from './form.vue'

  const { proxy } = getCurrentInstance()

  const data = reactive({
    moduleName: '字典类型',
    loading: true,
    ids: [],
    total: 0,
    listData: [],
    formData: null,
    formShow: false,
    searchForm: {
      pageNum: 1,
      pageSize: 10,
      like: { name: undefined, type: undefined },
      where: { status: undefined },
      time: { create_time: [] },
      orderByColumn: 'id',
      orderBySort: 'desc'
    }
  })

  const { moduleName, loading, ids, total, listData, formData, formShow, searchForm } = toRefs(data)

  onMounted(() => {
    getList()
  })

  // 查询列表
  function getList() {
    loading.value = true
    listTypeApi(searchForm.value).then(res => {
      listData.value = res?.list || []
      total.value = res?.total || 0
      loading.value = false
    })
  }

  // 搜索和重置
  function search() {
    searchForm.value.pageNum = 1
    getList()
  }

  // 新增和编辑
  function handleAdd() {
    formData.value = null
    formShow.value = true
  }
  function handleEdit(row) {
    const editId = row?.id || (ids.value.length ? ids.value[0] : '')
    if (!editId) return proxy.$modal.msgWarning('参数缺失')
    formData.value = { id: editId }
    formShow.value = true
  }

  // 删除按钮操作
  function handleDelete(row) {
    const delIds = row?.id || ids.value.join(',')
    if (!delIds) return proxy.$modal.msgWarning('未选择数据')
    proxy.$modal
      .confirm('是否确认删除字典编号为"' + delIds + '"的数据项？')
      .then(function () {
        return delTypeApi(delIds)
      })
      .then(() => {
        getList()
        proxy.$modal.msgSuccess('删除成功')
      })
      .catch(() => {})
  }

  // 多选框选中数据
  function handleSelection(selection) {
    ids.value = selection.map(item => item.id)
  }

  // 导出按钮操作
  function handleExport() {
    exportTypeApi(searchForm.value)
  }

  // 刷新缓存按钮操作
  function handleRefreshCache() {
    refreshCacheApi().then(() => {
      proxy.$modal.msgSuccess('刷新成功')
      useDictStore().cleanDict()
    })
  }

  // 跳转数据
  const router = useRouter()
  function toDictData(row) {
    if (!checkPerm(['system:dict-data:list'])) return proxy.$modal.msgWarning('权限不足')
    const id = row?.id || ''
    if (!id) return proxy.$modal.msgWarning('参数缺失')
    router.push({ name: 'DictData', params: { dictId: id } })
  }
</script>
